import 'dart:async';

import 'package:flutter/material.dart';
import 'package:xrenovation/api/auth.api.dart';
import 'package:xrenovation/localization/app_localizations.dart';
import 'package:xrenovation/routes.dart';
import 'package:xrenovation/utils/message_util.dart';
import 'package:xrenovation/widgets/custom_button.dart';
import 'package:xrenovation/widgets/custom_text_field.dart';

class ResetPage extends StatefulWidget {
  const ResetPage({super.key});

  @override
  State<ResetPage> createState() => _ResetPageState();
}

class _ResetPageState extends State<ResetPage> {
  final _formKey = GlobalKey<FormState>();
  final _emailController = TextEditingController();
  final _codeController = TextEditingController();
  final _passwordController = TextEditingController();

  bool _isSendingCode = false;
  bool _isResetting = false;
  int _countdown = 0;
  Timer? _timer;

  @override
  Widget build(BuildContext context) {
    final localizations = AppLocalizations.of(context);
    final theme = Theme.of(context);

    return Scaffold(
      appBar: AppBar(title: Text(localizations.translate('app_title'))),
      body: GestureDetector(
        onTap: () => FocusScope.of(context).unfocus(),
        behavior: HitTestBehavior.opaque,
        child: Center(
          child: SingleChildScrollView(
            padding: const EdgeInsets.symmetric(vertical: 18, horizontal: 24),
            child: ConstrainedBox(
              constraints: const BoxConstraints(maxWidth: 384),
              child: Column(
                children: [
                  _buildHeader(localizations, theme),
                  const SizedBox(height: 20),
                  _buildResetForm(localizations, theme),
                  const SizedBox(height: 50),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    _emailController.dispose();
    _codeController.dispose();
    _passwordController.dispose();
    _timer?.cancel();
    super.dispose();
  }

  Widget _buildHeader(AppLocalizations? localizations, ThemeData theme) {
    return Center(
      child: Column(
        children: [
          Container(
            width: 68,
            height: 68,
            decoration: BoxDecoration(color: theme.colorScheme.primary, borderRadius: BorderRadius.circular(34)),
            child: Center(
              child: Image.asset(
                'assets/images/logo.png',
                width: 52,
                height: 52,
                errorBuilder:
                    (context, error, stackTrace) =>
                        Icon(Icons.home_work_outlined, size: 52, color: theme.colorScheme.onPrimary),
              ),
            ),
          ),
          const SizedBox(height: 40),
          Text(
            localizations!.translate('reset_pwd_title'),
            style: theme.textTheme.headlineSmall?.copyWith(fontWeight: FontWeight.w600),
          ),
        ],
      ),
    );
  }

  Widget _buildResetForm(AppLocalizations? localizations, ThemeData theme) {
    return Form(
      key: _formKey,
      autovalidateMode: AutovalidateMode.onUserInteraction,
      child: Container(
        padding: const EdgeInsets.all(24),
        decoration: BoxDecoration(
          border: Border.all(color: theme.dividerColor),
          borderRadius: BorderRadius.circular(12),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 邮箱输入
            CustomTextField(
              label: localizations!.translate('email'),
              labelMark: true,
              controller: _emailController,
              hintText: localizations.translate('email_hintText'),
              keyboardType: TextInputType.emailAddress,
              validator: (value) {
                if (value == null || value.trim().isEmpty) {
                  // return '';
                  return localizations.translate('email_required');
                }
                if (!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(value)) {
                  // return '';
                  return localizations.translate('email_invalid');
                }
                return null;
              },
            ),
            const SizedBox(height: 4),
            Text(
              localizations.translate('email_desc'),
              style: theme.textTheme.bodySmall?.copyWith(color: theme.hintColor),
            ),

            // 验证码输入
            const SizedBox(height: 20),
            Row(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Expanded(
                  child: CustomTextField(
                    label: localizations.translate('email_code'),
                    labelMark: true,
                    hiddenErrorTip: true,
                    controller: _codeController,
                    keyboardType: TextInputType.number,
                    maxLength: 6,
                    hintText: localizations.translate('email_code_hintText'),
                    validator: (value) {
                      if (value == null || value.trim().isEmpty) {
                        return '';
                        // return localizations.translate('code_required');
                      }
                      return null;
                    },
                  ),
                ),
                const SizedBox(width: 10),
                SizedBox(
                  width: 120,
                  height: 48,
                  child:
                      _countdown > 0
                          ? CustomButton(title: '${localizations.translate('resend')} ($_countdown s)', onTap: null)
                          : CustomButton(
                            title: localizations.translate('send_code'),
                            onTap: _handleSendCode,
                            isLoading: _isSendingCode,
                          ),
                ),
              ],
            ),

            // 密码输入
            const SizedBox(height: 20),
            CustomTextField(
              label: localizations.translate('password'),
              labelMark: true,
              controller: _passwordController,
              keyboardType: TextInputType.visiblePassword,
              hintText: localizations.translate('pwd_hintText'),
              obscureText: true,
              validator: (value) {
                if (value == null || value.trim().isEmpty) {
                  // return '';
                  return localizations.translate('password_required');
                }
                if (value.length < 8) {
                  // return '';
                  return localizations.translate('password_length');
                }
                return null;
              },
            ),

            // 重置按钮
            const SizedBox(height: 20),
            CustomButton(
              title: localizations.translate('reset_pwd'),
              onTap: _handleResetPassword,
              isLoading: _isResetting,
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _handleResetPassword() async {
    final localizations = AppLocalizations.of(context);
    if (_isResetting) return;
    if (!(_formKey.currentState?.validate() ?? false)) return;

    final closeLoading = MessageUtil.loading('Resetting password...');

    try {
      setState(() => _isResetting = true);

      final response = await AuthApi.resetPassword(
        email: _emailController.text.trim(),
        code: _codeController.text.trim(),
        password: _passwordController.text.trim(),
      );

      closeLoading();

      if (response['code'] == 200) {
        MessageUtil.success(localizations.translate('reset_success_tip'));
        Navigator.pushReplacementNamed(context, AppRoutes.login);
      } else {
        MessageUtil.error(response['message'] ?? localizations.translate('reset_failed'));
      }
    } catch (e) {
      closeLoading();
      MessageUtil.error(localizations.translate('reset_failed'));
    } finally {
      if (mounted) setState(() => _isResetting = false);
    }
  }

  Future<void> _handleSendCode() async {
    final localizations = AppLocalizations.of(context);
    if (_isSendingCode || _countdown > 0) return;

    final email = _emailController.text.trim();
    if (email.isEmpty || !RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(email)) {
      MessageUtil.toast(localizations.translate('email_invalid'));
      return;
    }

    final closeLoading = MessageUtil.loading('Sending code...');

    try {
      setState(() => _isSendingCode = true);

      final response = await AuthApi.sendResetPasswordCode(email);

      closeLoading();

      if (response['code'] == 200) {
        MessageUtil.success(localizations.translate('send_success_tip'));
        _startCountdown();
      } else {
        MessageUtil.error(response['message'] ?? localizations.translate('send_code_failed'));
      }
    } catch (e) {
      closeLoading();
      MessageUtil.error(localizations.translate('send_code_failed'));
    } finally {
      if (mounted) setState(() => _isSendingCode = false);
    }
  }

  void _startCountdown() {
    setState(() => _countdown = 60);
    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_countdown > 0) {
        setState(() => _countdown--);
      } else {
        timer.cancel();
      }
    });
  }
}
